package com.neko.Thread_Learning;

import java.util.concurrent.locks.ReentrantLock;


public class t20_Lock {
    public static void main(String[] args) {

        TestLock testLock = new TestLock();

        new Thread(testLock).start();
        new Thread(testLock).start();
        new Thread(testLock).start();
    }

}

class TestLock implements Runnable {

    int ticketNums = 10;

    // 定义 用 ReentrantLock lcok
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {

            try {
                // 加锁
                lock.lock(); // <-- 用 ReentrantLock 锁住 调用对象

                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(ticketNums--);
                } else {
                    break;

                }

            } finally {
                // 解锁
                lock.unlock(); // <-- 解锁

            } // Lock.unlock() 必须写在 finally {...} 里面
        }

    }


}
